<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="院系代码">
        <el-input v-model="department.deptNo" maxlength="10"/>
      </el-form-item>
      <el-form-item label="院系名称">
        <el-input v-model="department.deptName"/>
      </el-form-item>
      <el-form-item label="院系位置">
        <el-input v-model="department.deptLocation"/>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="department.deptRemark"
          type="textarea"
          placeholder="请输入内容"
          maxlength="30"
          show-word-limit/>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
  .app-container{
    width: 500px;
  }
</style>

<script>
import department from '@/api/student/department'

const defaultForm = {
  deptNo: '',
  deptName: '',
  deptLocation: '',
  deptRemark: ''
}

export default {
  data() {
    return {
      department: defaultForm,
      saveBtnDisabled: false, // 保存按钮是否禁用,
      BASE_API: process.env.BASE_API // 接口API地址
    }
  },

  watch: {
    $route(to, from) {
      console.log('watch $route')
      this.init()
    }
  },

  created() {
    console.log('created .....')
    this.init()
  },

  methods: {
    init() {
      console.log('init .....')
      if (this.$route.params && this.$route.params.id) { // 更新
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else { // 新增
        // 使用对象拓展运算符，拷贝对象，而不是引用
        this.department = { ...defaultForm }
      }
    },
    // 保存
    saveOrUpdate() {
      this.saveBtnDisabled = true
      department.save(this.department).then(response => {
        console.log(response)
        return this.$message({
          type: 'success',
          message: response.message
        })
      }).then(resposne => {
        this.$router.push({ path: '/department' })
      })
    },

    // 根据id查询记录
    fetchDataById(id) {
      department.getById(id).then(response => {
        this.department = response.data.item
      })
    }

  }
}
</script>
